﻿package Component.BonusBlocks
{
	import Component.Map;
	import Map.BonusType;
	import Component.BonusPerms.BonusPerm;
	import Component.BonusPerms.BonusPerm_Bomb;
	import Component.BonusPerms.BonusPerm_Delay;
	import Component.BonusPerms.BonusPerm_Range;
	import Component.BonusPerms.BonusPerm_Speed;

	// there is one BonusBlock_Base per type per zone
	public class BonusBlock_Base
	{
		private var max_bonuses:uint;
		private var max_blocks:uint;

		private var clips:Vector.<BonusBlock_Item>;
		private var bonuses:Vector.<BonusPerm>;

		// drop chances
		private var bonus_remaining:uint;
		private var block_remaining:uint;
		private var luck_modifier:uint;

		public function BonusBlock_Base(map:Map,type:uint,max_bonuses:uint,max_blocks:uint)
		{
			clips = new Vector.<BonusBlock_Item>();
			bonuses = new Vector.<BonusPerm>();
			this.max_bonuses = max_bonuses;
			this.max_blocks = max_blocks;
			var bonus:BonusPerm;
			for(var index:uint = 0;index < max_bonuses;index++) {
				bonus = createBonus(type);
				bonuses.push(bonus);
				map.attach(bonus);
			}
		}

		public function reset()
		{
			bonus_remaining = max_bonuses;
			block_remaining = max_blocks;
			luck_modifier = 0;
			update();
		}

		// call this when a block is destroyed
		public function remove()
		{
			block_remaining--;
			luck_modifier++;
			update();
		}
		
		// call this when a bonus is dropped
		public function drop():BonusPerm {
			bonus_remaining--;
			luck_modifier = 0;
			return bonuses[bonus_remaining];
		}

		private function update()
		{
			var drop_chance:uint = bonus_remaining + luck_modifier / block_remaining + luck_modifier;
			var alpha:Number = 0;
			// colorize
			if (bonus_remaining > 0)
				alpha = 0.5 + 0.5 * (drop_chance);
			for each(var clip:BonusBlock_Item in clips)
				clip.alpha = alpha;
		}
		
		public function attach(mc:BonusBlock_Item) {
			mc._base = this;
			clips.push(mc);
		}
		
		public function clipAt(index:int):BonusBlock_Item {
			return clips[index];
		}

		private function createBonus(type:uint):BonusPerm {
			switch(type) {
				case BonusType.BOMB :
					return new BonusPerm_Bomb();
				break;
				case BonusType.DELAY :
					return new BonusPerm_Delay();
				break;
				case BonusType.RANGE :
					return new BonusPerm_Range();
				break;
				case BonusType.SPEED :
					return new BonusPerm_Speed();
				break;
			}
			return null;
		}
	}
}